var userInfo = null;
var tokenName = null;

$('#token-list').on('click', 'span', function () {
  $(this).addClass('select-active').siblings().removeClass('select-active');
  tokenName = $(this).html();
})


function signIn () {
  nebPay.simulateCall(dappAddress, "0", "getUserInfo", JSON.stringify([]), {
    listener: function(res) {
      if(res.result == '' && res.execute_err == 'contract check failed') {
          toast('合约检测失败，请检查浏览器钱包插件环境！');
          return;
      }
      
      var info = JSON.parse(JSON.parse(res.result));
      if (info) {
        userInfo = info;
        renderHTML(info);
        $('#loading').hide();
      }
    }
  })
}

signIn()

function renderHTML (info) {
  var html = '';
  for (var i = 0; i < info.token.length; i++) {
    html += '<span>'+info.token[i].tokenName+'</span>'
  }

  $('#token-list').html(html);
}

$('#send').on('click', function () {
  var to = $('#to').val();
  var num = $('#num').val();
  if (!to || !num || !tokenName) {
    toast('请将信息填写完整');
    return false
  }
  var tokenNum = 0;
  for (var i = 0; i < userInfo.token.length; i++) {
    if (userInfo.token[i].tokenName === tokenName.toUpperCase() && userInfo.token[i].tokenNum >= num) {
      tokenNum = userInfo.token[i].tokenNum;
    }
  }

  if (num <= tokenNum) {
    var hash = 'amz_hash' + Date.now() + ~~(Math.random() * 1e6);
    nebPay.call(dappAddress, "0", "transaction", JSON.stringify([tokenName, to, num, hash]), { 
      listener: function(res) {
        toast(res.txhash ? '转账成功,请稍等大约30秒可去查看交易哈希' : '转账失败！！！');
        $('#hash div').html(hash);
        $('#hash').show();
      }
    })
  } else {
    toast('余额不足')
  }
;})